/**
 * 
 */
package com.gametime.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.sql.rowset.CachedRowSet;

import com.sun.rowset.CachedRowSetImpl;


/**
 * @author dave
 *
 */
public class QueryRunner {

	/**
	 * @param args
	 */
	public CachedRowSetImpl query(String sql, Object[] params) throws Exception
	{
		
		Connection conn=null;
		try
		{
			conn = DBUtils.getInstance().getConnection();
			return query(conn, sql, params);
		}catch(Exception e)
		{
			e.printStackTrace();
			throw e;
		}finally
		{
			DBUtils.closeConnection(conn);
		}
	}
	
	public CachedRowSetImpl query(Connection conn, String sql, Object[] params)
	throws Exception
	{
		CachedRowSetImpl result= null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		try
		{
			
			ps = conn.prepareStatement(sql);
			if(params != null && params.length > 0)
			{
				for (int i=0;i<params.length;i++)
				{	Object o = params[i];
					if(o.getClass().equals(String.class))
					{
						ps.setString(i, o.toString());
					} else if(o.getClass().equals(Integer.class))
					{
						ps.setInt(i, (Integer)o);
					}else if(o.getClass().equals(Double.class))
					{
						ps.setDouble(i, (Double)o);
					}else if(o.getClass().equals(Float.class))
					{
						ps.setFloat(i, (Float)o);
					}else if(o.getClass().equals(Boolean.class))
					{
						ps.setBoolean(i, (Boolean)o);
					}else if(o.getClass().equals(java.sql.Date.class))
					{
						ps.setDate(i, (java.sql.Date)o);
					}else if(o.getClass().equals(Long.class))
					{
						ps.setLong(i, (Long)o);
					}else if(o.getClass().equals(Short.class))
					{
						ps.setShort(i, (Short)o);
					}else
					{
						ps.setObject(i, o);
					}
				}
				
			}
			rs = ps.executeQuery();
			result = new CachedRowSetImpl();
			result.populate(rs);
			
		}catch(Exception e)
		{
			throw e;
		}finally
		{
			try{
				rs.close();
			}catch(Exception e){}
			
			try{
				ps.close();
			}catch(Exception e){}
		}
		return result;
	}
	
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
